﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.MediaCenter.UI;
using System.Net;
using System.Xml.Linq;
using System.Runtime.InteropServices;
using System.IO;

namespace Playkanaler
{

    public class TV3Setting : ViasatSetting
    {
        public TV3Setting()
        {
            channel = ViasatChannel.TV3;
        }
    }
    public class TV6Setting : ViasatSetting
    {
        public TV6Setting()
        {
            channel = ViasatChannel.TV6;
        }
    }
    public class TV8Setting : ViasatSetting
    {
        public TV8Setting()
        {
            channel = ViasatChannel.TV8;
        }
    }
    public class SportSetting : ViasatSetting
    {
        public SportSetting()
        {
            channel = ViasatChannel.Sport;
        }
    }



    public enum ViasatChannel{Sport=1,TV3,TV6,TV8};

    public class Viasat
    {
        static string GetAdsXMLUrl(ViasatChannel channel, int prod_id)
        {
            return "http://eas7.emediate.eu/eas?cu_key=" + (int)channel + "se_" + prod_id.ToString() + ";ty=playlist;";
        }
        static string getAdClipUrl(string xmlurl)
        {
            WebClient wc = new WebClient();
            wc.Encoding = UTF8Encoding.UTF8;
            wc.Headers.Add("User-Agent", "Mozilla/4.0+");
            string txt = wc.DownloadString(xmlurl);
            txt = txt.Replace("&", "&amp;");
            XDocument xdoc = XDocument.Parse(txt);
           
            return xdoc.Element("ad").Element("url").Value;

        }

        public static string GetAdString(ViasatChannel ch, int id)
        {
            string adstr = "";
            WebClient wc = new WebClient();
            wc.Encoding = UTF8Encoding.UTF8;
            wc.Headers.Add("User-Agent", "Mozilla/4.0+");

           
         
            string txt = wc.DownloadString(GetAdsXMLUrl(ch, id));
            txt = txt.Replace("&", "&amp;");
            XDocument xdoc = XDocument.Parse(txt);
            
            foreach (XElement e in xdoc.Element("adcalls").Elements())
            {
                if (e.Name == "preroll" || e.Name == "postroll")
                {
                    int time = int.Parse(e.Attribute("time").Value);
                    time = time/1000;
                    adstr += "@" + time.ToString() + "=" + getAdClipUrl(e.Attribute("url").Value);
                }
                if (e.Name == "midrolls")
                {
                    foreach (XElement be in e.Elements("block"))
                    {
                        int time = int.Parse(be.Attribute("time").Value);
                        time = time / 1000;
                        string curl = be.Element("midroll").Attribute("url").Value;
                        adstr += "@" + time.ToString() + "=" + getAdClipUrl(curl);
                    }


                }
            }
            return adstr;



        }
    }

    public class ViasatSetting:Setting
    {
       public ViasatChannel channel = ViasatChannel.TV6;
       public int id = 0;
       public ViasatSetting()
       {
           View = new ListView();
           
       }
       public override void Load()
       {


           if (!Loaded)
           {
               if (id == 0)
               {
                   WebClient wc = new WebClient();
                   wc.Encoding = UTF8Encoding.UTF8;
                   wc.Headers.Add("User-Agent", "Mozilla/4.0+");
                   XDocument xdoc = new XDocument();
                   if (channel != ViasatChannel.Sport)
                   {
                       string doc = wc.DownloadString("http://viastream.viasat.tv/siteMapData/se/" + ((int)channel).ToString() + "se/" + id.ToString());
                       doc = doc.Replace("&", "&amp;");
                       xdoc = XDocument.Parse(doc);
                      

                   }
                   else
                   {
                       string doc = wc.DownloadString("http://viastream.player.mtgnewmedia.se/xml/xmltoplayer.php?type=siteMapData&channel=" + ((int)channel).ToString() + "se&country=se&category=" + id.ToString());
                       doc = doc.Replace("&", "&amp;");
                       xdoc = XDocument.Parse(doc);
                   }

                   View = new ListView();
                   Group g = new Group();

                   Tab t = new Tab(channel.ToString(), 0);
                   foreach (XElement e in xdoc.Element("siteMapData").Elements("siteMapNode"))
                   {
                       Item i = new Item(e.Attribute("title").Value, g.Count);
                       i.Attributes["id"] = int.Parse(e.Attribute("id").Value);
                       i.Title = i.Title.Replace("&amp;", "&");
                       g.Add(i);

                   }
                   t.Add(g);
                   Tabs.Add(t);
               }
               else
               {
                   WebClient wc = new WebClient();
                   wc.Encoding = UTF8Encoding.UTF8;
                   wc.Headers.Add("User-Agent", "Mozilla/4.0+");
                   XDocument xdoc =new XDocument();
                   if (channel != ViasatChannel.Sport)
                   {
                       string doc = wc.DownloadString("http://viastream.viasat.tv/siteMapData/se/" + ((int)channel).ToString() + "se/" + id.ToString());
                       doc = doc.Replace("&", "&amp;");
                       xdoc = XDocument.Parse(doc);
                   }
                   else
                   {
                       string doc = wc.DownloadString("http://viastream.player.mtgnewmedia.se/xml/xmltoplayer.php?type=siteMapData&channel=" + ((int)channel).ToString() + "se&country=se&category=" + id.ToString());
                       doc = doc.Replace("&", "&amp;");
                       xdoc = XDocument.Parse(doc);
                   }

                   View = new ListView();
                   Group g = new Group();
                  
                   foreach (XElement e in xdoc.Element("siteMapData").Elements("siteMapNode"))
                   {
                       ViasatProductTab vt = new ViasatProductTab(channel,int.Parse(e.Attribute("id").Value));
                       vt.Index = Tabs.Count;
                       vt.Title = e.Attribute("title").Value;
                       vt.Title = vt.Title.Replace("&amp;", "&");

                       Tabs.Add(vt);

                   }
               }
               if (Tabs.Count == 0)
               {
                   ViasatProductTab vt = new ViasatProductTab(channel, id);
                   vt.Index = Tabs.Count;
                   vt.Title = "alla";
                   Tabs.Add(vt);

               }
              
               SelectedTabIndex = 0;
               Loaded = true;
           }    
        }

       #region asd

       public delegate Boolean EnumChildProc(IntPtr hWnd, int lParam);


       public const uint WM_LBUTTONDOWN = 0x0201;
       public const uint WM_LBUTTONUP = 0x0202;

       [DllImport("user32.dll")]
       static extern IntPtr GetWindow(IntPtr hWnd, uint Msg);
       [DllImport("gdi32.dll")]
       static extern Int32 GetPixel(Int32 hdc, Int32 x, Int32 y);
       [DllImport("user32.dll")]
       static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
       [DllImport("user32.dll")]
        static extern IntPtr FindWindow(IntPtr lpszClass, string lpszWindow);
       [DllImport("user32.dll")]
       static extern IntPtr EnumChildWindows(IntPtr hwndParent, EnumChildProc enumChildProc, int lParam);
       [DllImport("user32.dll")]
       static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);
       [DllImport("user32.dll")]
       static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
       [DllImport("user32.dll")]
       static extern int GetClassName(IntPtr hWnd, StringBuilder text, int count);


       IntPtr flash = new IntPtr(0);
       Boolean EnumChildCB(IntPtr hWnd, int lParam)
       {
           StringBuilder sb = new StringBuilder(50);
           GetClassName(hWnd, sb, 50);
           if (sb.ToString() == "MacromediaFlashPlayerActiveX")
           {
               flash = hWnd;
           }

           return true;
       }
       IntPtr GetFlashWnd()
       {

           IntPtr window = new IntPtr(0);
           window = FindWindowEx(new IntPtr(0), new IntPtr(0), "eHome Render Window", null);
           EnumChildWindows(window, EnumChildCB, 0);

           return flash;
       }
       
        IntPtr GetFlashWnd(string tit)
       {
           IntPtr window = new IntPtr(0);
           window = FindWindow(new IntPtr(0), tit);
           EnumChildWindows(window, EnumChildCB, 0);

           return flash;

       }
       public bool clickWnd(int x, int y)
       {
           System.Threading.Thread.Sleep(1000);
           int lParam = (y << 16) + x;
           IntPtr hwnd = GetFlashWnd();

           // att göra: kolla färgen. om svart return false
           if (hwnd.ToInt32() == 0) return false;
           SendMessage(hwnd, 0x0200, 0x0, lParam);

           SendMessage(hwnd, WM_LBUTTONDOWN, 0x1, lParam);
           SendMessage(hwnd, 0x0200, 0x1, lParam);
           SendMessage(hwnd, WM_LBUTTONUP, 0x0, lParam);
           return true;
       }
       public bool clickWnd2(int x, int y, IntPtr hwnd)
       {
           System.Threading.Thread.Sleep(1000);
           int lParam = (y << 16) + x;
           

           // att göra: kolla färgen. om svart return false
           if (hwnd.ToInt32() == 0) return false;
           SendMessage(hwnd, 0x0200, 0x0, lParam);

           SendMessage(hwnd, WM_LBUTTONDOWN, 0x1, lParam);
           SendMessage(hwnd, 0x0200, 0x1, lParam);
           SendMessage(hwnd, WM_LBUTTONUP, 0x0, lParam);
           return true;
       }
       #endregion

       public override void ClickItem(Item item)
       {
           if (id == 0)
           {
               ViasatSetting vs = new ViasatSetting();
               vs.id = (int)item.Attributes["id"];
               vs.channel = channel;
               Dictionary<string, object> ps = new Dictionary<string, object>();
               ps.Add("Setting", vs);
               Microsoft.MediaCenter.Hosting.PageSession.Current.GoToPage("resx://Playkanaler/Playkanaler.Resources/Default#Default", ps);


           }
           else
           {
               string labba = "http://flvplayer.viastream.viasat.tv/flvplayer/play/swf/player100324.swf?affiliate=2se&country=se&id=" + item.Attributes["id"].ToString() + "&playerVersion=embed";
               //Microsoft.MediaCenter.Hosting.AddInHost.Current.MediaCenterEnvironment.NavigateToPage(Microsoft.MediaCenter.PageId.ExtensibilityUrl, labba);

               using(StreamWriter sw=new StreamWriter("c:\\playstr.txt"))
               {
                   sw.Write("http://flvplayer.viastream.viasat.tv/flvplayer/play/swf/player100324.swf?affiliate=2se&country= - Windows Internet Explorer");
               }

               System.Diagnostics.Process.Start("iexplore", labba);

               System.Threading.Thread.Sleep(1000);

               System.Threading.Thread.Sleep(1000);

               clickWnd2(300, 300, GetFlashWnd("http://flvplayer.viastream.viasat.tv/flvplayer/play/swf/player100324.swf?affiliate=2se&country= - Windows Internet Explorer")) ;

               //System.Diagnostics.Process.Start(Settings.Path + "capture.exe");

               System.Threading.Thread.Sleep(5000);
               foreach(var a in System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName()))
               {
                   
                   string ip=a.ToString();
                    Microsoft.MediaCenter.Hosting.AddInHost.Current.MediaCenterEnvironment.Dialog(ip,"IP", Microsoft.MediaCenter.DialogButtons.Ok,1000,true);
               }
//               Microsoft.MediaCenter.Hosting.AddInHost.Current.MediaCenterEnvironment.PlayMedia(Microsoft.MediaCenter.MediaType.Video,



               

               /*
               WebClient wc = new WebClient();
               wc.Encoding = UTF8Encoding.UTF8;
               wc.Headers.Add("User-Agent", "Mozilla/4.0+");
               XDocument xdoc = new XDocument();
               if (channel != ViasatChannel.Sport)
               {
                   string doc = wc.DownloadString("http://viastream.viasat.tv/Products/" + item.Attributes["id"].ToString());
                   doc = doc.Replace("&", "&amp;");
                   xdoc = XDocument.Parse(doc);
               }
               else
               {
                   string doc = wc.DownloadString("http://viastream.player.mtgnewmedia.se/xml/xmltoplayer.php?type=Products&clipid=" + item.Attributes["id"].ToString());
                   doc = doc.Replace("&", "&amp;");
                   xdoc = XDocument.Parse(doc);
               }


               string playstr = xdoc.Element("Products").Element("Product").Element("Videos").Element("Video").Element("Url").Value;

               XElement geo;
               if ((geo=xdoc.Element("Products").Element("Product").Element("Geoblock")) != null)
               {
                   if (geo.Value == "true")
                   {                      
                       xdoc = XDocument.Parse(wc.DownloadString(playstr));
                       playstr = xdoc.Element("GeoLock").Element("Url").Value;
                   }
               }

               playstr += Viasat.GetAdString(channel, int.Parse(item.Attributes["id"].ToString()));
               Play(playstr);
                */ 
                   
                   

           }
           
       }




    }

    
    public class ViasatProductTab : Tab
    {
        public ViasatProductTab()
        {
            Title = "";
        }
        int id = 0;
        
        ViasatChannel channel;
        public ViasatProductTab(ViasatChannel vc, int _id)
        {
            id = _id;
            channel = vc;

            IsLoaded = false;

        }
        
        public override void Load()
        {
            if (!IsLoaded)
            {
                WebClient wc = new WebClient();
                wc.Encoding = UTF8Encoding.UTF8;
                wc.Headers.Add("User-Agent", "Mozilla/4.0+");
                XDocument xdoc = new XDocument();


                if (channel != ViasatChannel.Sport)
                {
                    string doc = wc.DownloadString("http://viastream.viasat.tv/Products/Category/" + id.ToString());
                    doc = doc.Replace("&", "&amp;");
                    xdoc = XDocument.Parse(doc);
                }
                else
                {
                    string doc = wc.DownloadString("http://viastream.player.mtgnewmedia.se/xml/xmltoplayer.php?type=Products&category=" + id.ToString());
                    doc = doc.Replace("&", "&amp;");
                    xdoc = XDocument.Parse(doc);                   
                }
                
                View = new ListView();
                Group g = new Group();
                
                foreach (XElement e in xdoc.Element("Products").Elements("Product"))
                {
                    Item i = new Item(id.ToString() + " " + e.Element("Title").ToString(), g.Count);
                    i.Title = i.Title.Substring(i.Title.LastIndexOf('[')+1);
                    i.Title = i.Title.Remove(i.Title.IndexOf(']'));
                    i.Title = i.Title.Replace("&amp;", "&");

                    i.Attributes["id"] = int.Parse(e.Element("ProductId").Value);
                    g.Add(i);

                }
                Add(g);
                IsLoaded = true;
            }
        }

    }

 
}
